package co.baiku.boot.core.orm.tools;

import co.baiku.boot.common.message.PageData;
import co.baiku.boot.common.spring.SpringContext;
import co.baiku.boot.common.tools.ObjectTools;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;

import javax.persistence.EntityManager;
import java.util.Map;

public class JpaTools {

    public static EntityManager getEntityManager() {
        return SpringContext.getBean(EntityManager.class);
    }

    /**
     * 构造排序规则
     *
     * @return
     */
    public static Sort sort(Map<String, String> sortBy) {
        if (ObjectTools.isNotBlank(sortBy)) {
            Sort sort = null;
            for (Map.Entry<String, String> sortByEntry : sortBy.entrySet()) {
                String name = sortByEntry.getKey();
                String direction = sortByEntry.getValue();
                Sort sortAnd = Sort.by(Sort.Direction.fromString(direction), name);
                if (sort == null) {
                    sort = sortAnd;
                } else {
                    sort = sort.and(sortAnd);
                }
            }
            if (sort == null) {
                return Sort.unsorted();
            } else {
                return sort;
            }
        }
        return Sort.unsorted();
    }

    /**
     * 根据jpa返回和当前分页请求生成分页消息
     *
     * @param page
     * @param <T>
     * @return
     */
    public static <T> PageData toPageData(Page<T> page) {
        return PageData.of(page.getNumber() + 1, page.getNumberOfElements(), (int) page.getTotalElements(), page.getContent());
    }
}
